要如何把昨天的Console端程式轉換為Swing版本呢?
其實道理與猜數字遊戲大同小異,我們一樣先來想加入使用者互動的流程。
流程相對猜數字其實簡單了許多-
使用者在文字方塊中輸入攝氏溫度 -> 按下"求華式溫度"的按鈕 -> 下方處顯示華氏溫度
使用者按下"清除"按鈕 -> 清除文字方塊中的文字
與猜數字相同,我們一樣將專案分為主函式檔CtoF.java與主要邏輯檔Convertor.java
Convertor.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Convertor {
 private JFrame frame;
 private JLabel lab;
 private JLabel lab2;
 private JButton bot;
 private JButton bot1;
 private JTextField te;
 
 public Swing() {
  frame = new JFrame("攝氏轉華氏溫度");
  frame.setLayout(null);
  
  lab = new JLabel("請輸入攝氏溫度:");
  lab.setBounds(5, 5, 100, 20);
  frame.add(lab);
  
  te = new JTextField();
  te.setBounds(107, 5, 100, 20);
  frame.add(te);
  
  bot = new JButton("求華氏溫度");
  bot.setBounds(5, 37, 100, 20);
  frame.add(bot);
  
        lab2 = new JLabel("");
        lab2.setBounds(5, 59, 200, 40); 
        frame.add(lab2); 
  
  bot.addActionListener(new ActionListener() {
   @Override
   public void actionPerformed(ActionEvent e) {
     try {
      double c = Double.parseDouble(te.getText());
      double f = (9.0/5.0)*c+32;
      lab2.setText("華氏溫度: "+f);
     }catch(Exception e1) {
      
     }
    }  
  });
  
  bot1= new JButton("清除");
  bot1.setBounds(107, 37, 100, 20);
  frame.add(bot1);
  
  bot1.addActionListener(new ActionListener() {
   @Override
   public void actionPerformed(ActionEvent e) {
    te.setText("");
    lab2.setText("");
   }  
  });
  frame.setSize(400, 200);
  frame.setVisible(true);
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  
 }
}
CtoF.java
public class CtoF {
	public static void main(String[] args) {
		new Swing();
	}
}
Hi, I am Grant.
個人部落格 - https://grantliblog.wordpress.com/
個人網站 - https://grantli-website.netlify.app/#/mainpage
我的寫作專題 - https://vocus.cc/user/5af2e9b5fd89780001822db4#